package com.shanshan.community.controller;


import com.shanshan.community.entity.DiscussPost;
import com.shanshan.community.entity.Page;
import com.shanshan.community.entity.User;
import com.shanshan.community.service.DiscussPostService;
import com.shanshan.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public String getIndexPage(Model model, Page page) {
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");

        List<DiscussPost> disCussPosts = discussPostService.findDisCussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String, Object>> list = new ArrayList<>();
        if (disCussPosts != null) {
            for (DiscussPost disCussPost : disCussPosts) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("post", disCussPost);
                //根据post里面的userId获取到具体的user
                User user = userService.findUserById(disCussPost.getUserId());
                map.put("user", user);
                list.add(map);
            }
        }
        model.addAttribute("discussPost", list);
        return "index";
    }
}
